package cn.togeek.generate.controller;

import lombok.extern.slf4j.Slf4j;

import cn.togeek.generate.api.model.GenerateCodeDTO;
import cn.togeek.generate.api.model.TablePageDTO;
import cn.togeek.generate.api.service.ICodeGenerateService;
import cn.togeek.generate.util.PageResult;
import cn.togeek.generate.util.R;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author hanle
 * @description
 * @date 2021/8/3 10:30
 * @Company 西安图迹信息科技有限公司
 */
@Slf4j
@RestController
@RequestMapping("/sys/generate")
public class CodeGenerateController {

   @Autowired
   private ICodeGenerateService codeGenerateService;


   @GetMapping("/page")
   public R queryTables(TablePageDTO dto) {
      PageResult page = codeGenerateService.queryTables(dto);
      return R.ok().put("data", page);
   }

   @GetMapping("/build")
   public void buildCode(@Valid GenerateCodeDTO dto, HttpServletResponse response) throws IOException {
      byte[] data = codeGenerateService.buildCode(dto.getTables().split(","));
      response.reset();
      response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
      response.addHeader("Content-Length", "" + data.length);
      response.setContentType("application/octet-stream; charset=UTF-8");
      IOUtils.write(data, response.getOutputStream());
   }

}
